﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using System.Configuration;
using NLog;
using System.Security.Cryptography;

namespace com.dc.url
{
    public class UrlRewriteModule : IHttpModule
    {
        /// <summary>
        /// 日志对象
        /// </summary>
        static Logger m_log = LogManager.GetLogger("sys_log");
        /// <summary>
        /// 章节内容地址
        /// </summary>
        string chapter = @"(http:)\/\/(\S+)\/(\d+)\/(\d+)\/(\d+)\.txt\?key=(\S+)";

        string errorUrl = @"~/error.txt";

        string urlkey = ConfigurationManager.AppSettings["UrlKey"] == null ? "@!%$tyh20114" : ConfigurationManager.AppSettings["UrlKey"].ToString();

        /// <summary>
        /// 请求初始
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(BeginRequestHandler);
        }
        public void Dispose()
        {
            // throw new Exception( "The method or operation is not implemented." );
        }

        /// <summary>
        /// 生成Md5签名
        /// </summary>
        /// <param name="srcText"></param>
        /// <returns></returns>
        public static string MD5Mac(string srcText)
        {


            MD5 myMD5 = new MD5CryptoServiceProvider();
            byte[] HashCode;
            HashCode = Encoding.Default.GetBytes(srcText);
            HashCode = myMD5.ComputeHash(HashCode);

            StringBuilder EnText = new StringBuilder();
            foreach (byte Byte in HashCode)
            {
                EnText.AppendFormat("{0:x2}", Byte);
            }

            return EnText.ToString().ToUpper();
        }


        private void BeginRequestHandler(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpRequest request = HttpContext.Current.Request;

           
            string url = request.Url.ToString().ToLower();

            m_log.Info(url);
            if (url.IndexOf(".txt") < 0) return;
            if (url.IndexOf("error") > -1) return;
            try
            {

                Match t_mc = Regex.Match(url,chapter, RegexOptions.IgnoreCase | RegexOptions.Compiled);

                if (t_mc == null || t_mc.Groups.Count != 7)
                {
                    m_log.Info(string.Format("{0} 非法访问", UserTrueIp));
                    HttpContext.Current.Response.Redirect(errorUrl, false);
                    return;
                }

                string t_mac = t_mc.Groups[6].Value.ToString().ToLower();
                string t_category_id = t_mc.Groups[3].Value.ToString();
                string t_book_id = t_mc.Groups[4].Value.ToString();
                string t_chapter_id = t_mc.Groups[5].Value.ToString();

                string t_real_mac = MD5Mac(string.Format("{0}_{1}_{2}_{3}", t_category_id, t_book_id, t_chapter_id, urlkey));

                if (t_mac.ToLower().Equals(t_real_mac.ToLower()) == false)
                {
                    m_log.Info(string.Format("{0} 非法访问", UserTrueIp));
                    HttpContext.Current.Response.Redirect(errorUrl, false);
                    return;
                }

                //string realUrl = Regex.Replace(url, chapter, "~/$3/$4/$5.txt", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                //m_log.Info(realUrl);
                //HttpContext.Current.RewritePath(realUrl);
                //return;

            }
            catch (Exception ex)
            {
                m_log.Error("重写url出现异常" + ex.ToString());
                return;
            }

        }

        public  string SquidForwardIp
        {
            get
            {
                //string netSCalerIp=  HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];
                //if (!string.IsNullOrEmpty(netSCalerIp))
                //    return netSCalerIp;

                string forwordList = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(forwordList))
                    return string.Empty;

                string[] ipList = forwordList.Split(new char[] { ',' });
                if (ipList.Length >= 2 && !ipList[0].Equals("unknown"))
                {
                    return ipList[0];
                }
                else if (ipList.Length >= 2 && !ipList[1].Equals("unknown"))
                {
                    return ipList[1];
                }
                else if (ipList.Length == 1 && !ipList[0].Equals("unknown"))
                {
                    return ipList[0];
                }
                else if (!forwordList.StartsWith("10.") && !forwordList.StartsWith("unknown"))
                {
                    return forwordList;
                }
                else
                {
                    return string.Empty;
                }
            }
        }

        /// <summary>
        /// 获取用户真实的ip
        /// </summary>
        public  string UserTrueIp
        {
            get
            {
                if (HttpContext.Current != null && HttpContext.Current.Request != null)
                {
                    if (!string.IsNullOrEmpty(SquidForwardIp)) return SquidForwardIp.Trim();

                    string trueIp = HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];
                    if (string.IsNullOrEmpty(trueIp))
                        trueIp = HttpContext.Current.Request.UserHostAddress;

                    return trueIp.Trim();
                }
                else
                    return string.Empty;
            }
        }

    }
}
